package com.wzh.easyapi.service;

import cn.hutool.json.JSONUtil;
import com.wzh.easyapi.bean.DataSourceEntity;
import com.wzh.easyapi.bean.SqlManage;
import com.wzh.easyapi.config.DataSourceContextHolder;
import com.wzh.easyapi.config.DruidDataSourceManager;
import com.wzh.easyapi.exception.ServiceException;
import com.wzh.easyapi.form.SQLRequest;
import com.wzh.easyapi.form.SqlParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.rmi.ServerException;
import java.sql.Connection;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class DynamicSQLService {

    private final DruidDataSourceManager dataSourceManager;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DataSourceService dataSourceService;

    public DynamicSQLService(DruidDataSourceManager dataSourceManager) {
        this.dataSourceManager = dataSourceManager;
    }

    public List<Map<String, Object>> executeSQL(SqlManage sqlManage) {
        DataSource dataSource = getDataSource(dataSourceService.getById(sqlManage.getDatasourceId()));

        // 动态切换数据源
        DataSourceContextHolder.setDataSourceKey(sqlManage.getDatasourceId());
        try {
            NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
            // 将 SqlParam 转换为 MapSqlParameterSource
            MapSqlParameterSource paramSource = convertToParamSource(JSONUtil.toList(sqlManage.getSqlParams(),SqlParam.class));
            // 使用 NamedParameterJdbcTemplate 执行 SQL
            return namedParameterJdbcTemplate.queryForList(sqlManage.getSqlEncode(), paramSource);
        }catch (Exception e){
            log.error(e.getMessage());
            throw new ServiceException(e.getMessage());
        }finally {
            // 清除上下文
            DataSourceContextHolder.clear();
        }
    }

    private MapSqlParameterSource convertToParamSource(List<SqlParam> sqlParams) {
        MapSqlParameterSource paramSource = new MapSqlParameterSource();
        if (sqlParams != null) {
            for (SqlParam param : sqlParams) {
                if (param.getKey() != null && param.getValue() != null) {
                    log.info("Adding SQL parameter: key = {}, value = {}", param.getKey(), param.getValue());
                    paramSource.addValue(param.getKey(), param.getValue());
                }
            }
        }
        return paramSource;
    }


    public DataSource getDataSource(DataSourceEntity dataSource) {
        return dataSourceManager.getDataSource(dataSource,false);
    }


    public Boolean testConnection(DataSource dataSource) {
        // 测试连接
        try (Connection connection = dataSource.getConnection()) {
            if (connection.isValid(2)) {
                log.info("连接成功");
            }
            return true;
        } catch (Exception e) {
           throw new ServiceException(e.getMessage());
        }
    }
}
